package service

import (
	"errors"
	"time"

	"mutu/misc"
	"mutu/misc/conf"
	"mutu/misc/log"
	"mutu/models"
)

var (
	SessionExpire = conf.GetInt("SessionExpire")
)

type SessionManager struct {
}

var (
	SessionService = SessionManager{}
)

func (p SessionManager) CreateSession(user *models.User, auth *models.Auth) (*models.Session, error) {
	ses := &models.Session{
		Uuid:   misc.NewUUID(),
		UserId: user.Uuid,
		Nick:   user.Nick,
		Himg:   user.Himg,
		Flag:   auth.Flag,
		OpenId: auth.OpenId,

		Live:   SessionExpire,
		Expire: false,

		ExpireAt: misc.GTimer.Now.Add(time.Duration(SessionExpire) * time.Second),
	}

	_, err := models.Orm.Insert(ses)
	return ses, err
}

func (p SessionManager) QuerySession(uuid string) (*models.Session, error) {
	ses := &models.Session{
		Uuid: uuid,
	}
	if err := models.Orm.Read(ses, "Uuid"); err != nil {
		return nil, err
	}
	if ses.Expire {
		return nil, errors.New("会话过期")
	}
	log.Log.Debug("ses expireat: %v, %d\n", ses.ExpireAt, ses.ExpireAt.Unix())
	log.Log.Debug("curtime : %v, %d\n", misc.GTimer.Now, misc.GTimer.Unix)
	//if !ses.ExpireAt.Before(misc.GTimer.Now) {
	if ses.ExpireAt.Unix() <= misc.GTimer.Unix {
		ses.Expire = true
		models.Orm.Update(ses, "Expire", "UpdateAt")
		return nil, errors.New("会话过期")
	}
	return ses, nil

}

func (p SessionManager) RemoveSession(ses *models.Session) error {

	ses.Expire = true
	_, err := models.Orm.Update(ses, "Expire", "UpdateAt")
	return err

}
